package com.zcf.order.controller;

import com.zcf.entity.service2.major.entity.TOrderTbl;
import com.zcf.order.feign.AccountClient;
import com.zcf.order.service.OrderService;
import io.seata.core.context.RootContext;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author zhaochaofeng
 * @version 1.0
 * @date 2020/9/16 11:30
 */
@Log4j2
@RestController
public class OrderController {
    private static final String USER_ID = "U100001";
    @Autowired
    private OrderService orderService;
    @Resource
    private AccountClient accountClient;

    @PostMapping(value = "/order", produces = "application/json")
    public String order(String userId, String commodityCode, int orderCount) {
        log.info("Order Service Begin ... xid: " + RootContext.getXID());

        int orderMoney = calculate(orderCount);

//        String result = accountClient.consumption(USER_ID, orderMoney);
//        if(!"SUCCESS".equals(result)){
//            throw new RuntimeException("account-service consumption is error");
//        }

        TOrderTbl orderTbl = new TOrderTbl();
        orderTbl.setCommodityCode(commodityCode);
        orderTbl.setUserId(userId);
        orderTbl.setCount(orderCount);
        orderTbl.setMoney(orderMoney);

        boolean flag = orderService.addOrder(orderTbl);

        log.info("Order Service End ... Created " + orderTbl);

        if (flag) {
            return "SUCCESS";
        }
        return "FAIL";
    }

    private int calculate(int orderCount) {
        return 2 * orderCount;
    }

}
